import 'dart:io';
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_number/mobile_number.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/user.dart';
import 'package:device_info/device_info.dart';
import 'package:http/http.dart' as http;

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool _hasServer = false;
  bool _isChecking = false;

  initState() {
    super.initState();
    _checkServer();
  }

  _checkServer() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _hasServer = prefs.containsKey('server');
    });
  }

  _setServer() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final res = await showTextInputDialog(context: context, title: '请输入接口地址', textFields: [
      DialogTextField(initialText: prefs.containsKey('server') ? prefs.getString('server') : 'http://'),
    ]);
    if (res != null) {
      try {
        setState(() {
          _isChecking = true;
        });
        await http.get(Uri.parse(res.first + '/status'));
        prefs.setString('server', res.first);
        setState(() {
          _hasServer = true;
          _isChecking = false;
        });
      } catch (e) {
        setState(() {
          _isChecking = false;
        });
        await showOkAlertDialog(context: context, title: '严重错误', message: '接口不通，请重新输入');
        await _setServer();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final _user = context.watch<User>();

    return Scaffold(
      body: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/bg.jpeg'),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(bottom: 200.0),
                child: Text(
                  '家庭理财簿',
                  style: TextStyle(
                    fontSize: 60.0,
                    fontFamily: 'HappyFont',
                    color: Colors.white,
                    letterSpacing: 6.0,
                    shadows: <Shadow>[
                      Shadow(color: Colors.grey, offset: Offset(1, 1)),
                    ],
                  ),
                ),
              ),
              _hasServer
                  ? ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        padding: WidgetStateProperty.all(EdgeInsets.symmetric(vertical: 10.0, horizontal: 52.0)),
                      ),
                      child: Text(
                        '本机号码登录',
                        style: TextStyle(fontSize: 22, color: Colors.white),
                      ),
                      onPressed: () async {
                        if (Platform.isIOS) {
                          IosDeviceInfo _info = await DeviceInfoPlugin().iosInfo;
                          _user.deviceId = _info.identifierForVendor;
                        } else if (Platform.isAndroid) {
                          AndroidDeviceInfo _info = await DeviceInfoPlugin().androidInfo;
                          _user.deviceId = _info.androidId;
                        }
                        await _user.exist();
                        String? _mobileNumber;
                        if (_user.id != null) {
                          _mobileNumber = _user.phone;
                        } else if (Platform.isAndroid) {
                          try {
                            _mobileNumber = await MobileNumber.mobileNumber;
                            if (_mobileNumber != null && _mobileNumber.length > 0) {
                              _mobileNumber = _mobileNumber.substring(_mobileNumber.length - 11);
                            } else {
                              _mobileNumber = null;
                            }
                          } on PlatformException catch (_) {}
                        }
                        if (_mobileNumber != null) {
                          final res = await showOkCancelAlertDialog(
                            context: context,
                            title: '确定删除?',
                            message: '是否以' + _mobileNumber + '登录?',
                          );
                          if (res == OkCancelResult.ok) {
                            _user.phone = _mobileNumber;
                            await _user.login();
                          }
                        } else {
                          await showOkAlertDialog(
                            context: context,
                            title: '设备唯一码',
                            message: '请联系管理员添加设备, 设备码为: ${_user.deviceId.toString()}',
                          );
                        }
                      })
                  : SizedBox(),
              SizedBox(
                height: 28,
              ),
              ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all(Colors.orange),
                    padding: WidgetStateProperty.all(EdgeInsets.symmetric(vertical: 10.0, horizontal: 52.0)),
                  ),
                  child: Text(
                    _isChecking
                        ? '验证服务器中...'
                        : _hasServer
                            ? '重设服务器地址'
                            : '设置服务器地址',
                    style: TextStyle(fontSize: 22, color: Colors.white),
                  ),
                  onPressed: _isChecking ? null : _setServer),
            ],
          )),
    );
  }
}
